"""Goup that tracks the position of one sprite"""
import pygame, math
import vecmath

class Camera(pygame.sprite.GroupSingle):
    """Tracks a given sprites to center it on the screen"""
    MAX_DISTANCE = 1000 # sample max distance, to compare to others
    _M_SQDIST = MAX_DISTANCE**2
        
    def __init__(self, sprite=None):
        pygame.sprite.GroupSingle.__init__(self, sprite)
        self.vp_dimensions = (game.dimensions.w / 2, game.dimensions.h / 2)
        self.nearest_sq_distance = 0
        self.zoom_enabled = 1

    def speed(self):
        if self.sprite:
            return self.sprite.speed
        else:
            return (0, 0)
    
    def position(self):
        if self.sprite:
            return self.sprite.position
        else:
            return (0, 0)
    
    def update(self):
        """updates the game viewport position to the current followed sprite
        position and sets the zooming level depending on the distance of the
        nearest foe"""
        if self.sprite:
            game.vp = (self.sprite.position[0] * game.zoom - self.vp_dimensions[0],\
                       self.sprite.position[1] * game.zoom - self.vp_dimensions[1])
            
        if(self.zoom_enabled):
            if(self.nearest_sq_distance >= 0):
                game.zoom = 1 - math.sqrt(self.nearest_sq_distance / self._M_SQDIST)
                
                if game.zoom < 0.3:
                    game.zoom = 0.3
                elif game.zoom < 0.6 and game.zoom > 0.35:
                    game.zoom = 0.6
                elif game.zoom > 0.65:
                    game.zoom = 1.
                
            self.nearest_sq_distance = self._M_SQDIST # reset the max distance

    def check_distance(self, tg):
        """Method to be called from each ship, checks if the distance between it
        and the followed ship to set the zoom on the next game tick"""
        
        if self.zoom_enabled and self.sprite:
            if tg.__module__ != self.sprite.__module__:
                n = vecmath.sqdist(self.sprite.position, tg.position)
                if(n > 0 and n < self.nearest_sq_distance):
                    self.nearest_sq_distance = n

import game